package service

import (
	"RedisManager/internal/define"
	"RedisManager/internal/helper"
	"context"
)

// KeyList 键列表
func KeyList(req *define.KeyListRequest) ([]string, error) {
	rdb, err := helper.GetRedisClient(req.ConnIdentity, req.Db)
	var count = define.DefaultKeyLen
	if req.Keyword != "" {
		count = define.MaxKeyLen
	}
	res, _, err := rdb.Scan(context.Background(), 0, "*"+req.Keyword+"*", count).Result()
	if err != nil {
		return nil, err
	}
	return res, nil
}

// GetKeyValue 获取键值对
func GetKeyValue(req *define.KeyValueRequest) (*define.KeyValueReply, error) {
	rdb, err := helper.GetRedisClient(req.ConnIdentity, req.Db)
	_type, err := rdb.Type(context.Background(), req.Key).Result()
	if err != nil {
		return nil, err
	}
	var reply = &define.KeyValueReply{
		Type: _type,
	}
	if _type == "string" {
		v, err := rdb.Get(context.Background(), req.Key).Result()
		if err != nil {
			return nil, err
		}
		reply.Value = v
	}
	ttl, err := rdb.TTL(context.Background(), req.Key).Result()
	if err != nil {
		return nil, err
	}
	if ttl == -1 {
		reply.TTL = ttl
	} else {
		reply.TTL = ttl / 1000000000
	}
	return reply, nil
}

// DeleteKeyValue 删除键值对
func DeleteKeyValue(req *define.KeyValueRequest) error {
	rdb, err := helper.GetRedisClient(req.ConnIdentity, req.Db)
	_, err = rdb.Del(context.Background(), req.Key).Result()
	return err
}

// CreateKeyValue 创建键值对
func CreateKeyValue(req *define.CreateKeyValueRequest) error {
	rdb, err := helper.GetRedisClient(req.ConnIdentity, req.Db)
	if req.Type == "string" {
		err = rdb.Set(context.Background(), req.Key, "value", 0).Err()
	}
	return err
}

// UpdateKeyValue 更新键值对数据
func UpdateKeyValue(req *define.UpdateKeyValueRequest) error {
	rdb, err := helper.GetRedisClient(req.ConnIdentity, req.Db)
	// type ==> string
	if req.TTL == -1 {
		req.TTL = 0
	}
	err = rdb.Set(context.Background(), req.Key, req.Value, req.TTL).Err()
	return err
}
